<template>
  <div>
    <div
      class="padding20 whiteBg br-8 category_type_tabs"
      v-if="categoryTypeOptions.length"
    >
      <el-tabs
        v-model="activeCategoryTypeCode"
        @tab-change="handleCategoryTypeChange"
        type="card"
      >
        <el-tab-pane
          v-for="item in categoryTypeOptions"
          :key="item.code"
          :label="item.name || item.description || item.code"
          :name="item.code"
        />
      </el-tabs>
    </div>
    <!-- 搜索区域 -->
    <div class="padding20 whiteBg br-8">
      <el-row class="search_block" :gutter="20">
        <el-col :span="8">
          <span class="label_text">编号：</span>
          <el-input v-model="searchParams.code" clearable placeholder="请输入编号" style="width: calc(100% - 90px)"
            maxlength="20">
          </el-input>
        </el-col>
        <el-col :span="8">
          <span class="label_text">名称：</span>
          <el-input v-model="searchParams.name" clearable placeholder="请输入名称" style="width: calc(100% - 90px)"
            maxlength="20">
          </el-input>
        </el-col>
        <el-col :span="8">
          <span class="label_text">类型：</span>
          <el-select v-model="searchParams.level" clearable placeholder="全部" style="width: calc(100% - 90px)">
            <el-option label="全部" value=""></el-option>
            <el-option label="大类" value="1"></el-option>
            <el-option label="中类" value="2"></el-option>
            <el-option label="品类" value="3"></el-option>
            <el-option label="商品" value="4"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row class="search_block m-t-10" :gutter="20">
        <el-col :span="8">
          <span class="label_text">状态：</span>
          <el-select v-model="searchParams.status" clearable placeholder="全部" style="width: calc(100% - 90px)">
            <el-option label="全部" value="" />
            <el-option label="已生效" value="1" />
            <el-option label="已停用" value="0" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <span class="label_text">&nbsp;</span>
        </el-col>
        <el-col :span="8">
          <div class="flex_item right search_btn_group">
            <el-button @click="handleReset">清空</el-button>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格操作区和表格 -->
    <div class="m-t-16 whiteBg padding20 br-8">
      <div class="table_operation" style="margin-bottom: 16px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button class="btn_plain" type="primary" plain @click="handleExport">导出</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table class="list_table" :data="listData" border v-loading="pageParam.loading" style="width: 100%"
        :header-cell-class-name="handleHeaderCellClass">
        <el-table-column prop="categoryCode" label="编号" width="180" fixed="left">
          <template #default="scope">
            <el-button link type="primary" @click="handleViewDetail(scope.row)">
              {{ scope.row.categoryCode || '--' }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column prop="categoryName" label="名称" width="164">
          <template #default="scope">
            {{ scope.row.categoryName || '--' }}
          </template>
        </el-table-column>

        <el-table-column prop="parentCategoryCode" label="上级分类编号" width="180">
          <template #default="scope">
            {{ scope.row.parentCategoryCode || '--' }}
          </template>
        </el-table-column>

        <el-table-column prop="parentCategoryName" label="上级分类名称" width="180">
          <template #default="scope">
            {{ scope.row.parentCategoryName || '--' }}
          </template>
        </el-table-column>

        <el-table-column prop="level" label="类型" width="100" align="center">
          <template #default="scope">
            {{ getLevelName(scope.row.level) }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态"  align="center">
          <template #default="scope">
            {{ getStatusLabel(scope.row) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              link
              type="primary"
              @click="handleStatusChange(scope.row)"
              v-if="getStatusValue(scope.row) === 0"
            >
              启用
            </el-button>
            <el-button link type="primary" @click="handleStatusChange(scope.row)" v-else>
              停用
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="m-t-24 align-right">
        <el-pagination background v-model:current-page="pageParam.pageNo" v-model:page-size="pageParam.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          :total="Number(pageParam.total)" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getToken } from '@/utils/auth';
import { downloadFile } from '@/utils/func';
import {
  getCategoryTypes,
  getCategoryList,
  toggleCategoryStatus,
} from '@/api/categoryManagement';
const router = useRouter();
const { proxy } = getCurrentInstance();
const $api = proxy?.$api;
const DEFAULT_CATEGORY_TYPE_CODE = 'basic';
const categoryTypeOptions = ref([]);
const activeCategoryTypeCode = ref('');

// 搜索参数初始化
const initialSearchParams = {
  code: '',
  name: '',
  level: '',
  status: '',
};

const searchParams = reactive({ ...initialSearchParams });

// 分页参数
const pageParam = reactive({
  loading: false,
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

// 数据和状态
const listData = ref([]);
const sortField = new Map();

/**
 * 获取分类类型 tabs
 */
const getCategoryTypeTabs = async () => {
  try {
    const res = await getCategoryTypes(true);
    const mapped = (res.data || []).map((item) => ({
      code: item.code,
      name: item.description || item.code,
      remark: item.extendedField1,
    }));
    categoryTypeOptions.value = mapped;
    if (!activeCategoryTypeCode.value) {
      activeCategoryTypeCode.value =
        mapped[0]?.code || DEFAULT_CATEGORY_TYPE_CODE;
    }
  } catch (error) {
    console.error('获取分类类型失败:', error);
    if (!activeCategoryTypeCode.value) {
      activeCategoryTypeCode.value = DEFAULT_CATEGORY_TYPE_CODE;
    }
  }
};

/**
 * 查询列表数据
 */
const getListData = async () => {
  pageParam.loading = true;
  try {
    // 构建请求参数
    const params = {
      categoryCode: searchParams.code || undefined,
      categoryName: searchParams.name || undefined,
      level: searchParams.level ? Number(searchParams.level) : undefined,
      status:
        searchParams.status !== '' ? Number(searchParams.status) : undefined,
      categoryTypeCode:
        activeCategoryTypeCode.value || DEFAULT_CATEGORY_TYPE_CODE,
      pageNo: pageParam.pageNo,
      pageSize: pageParam.pageSize,
    };

    // 移除 undefined 的参数
    Object.keys(params).forEach(
      (key) => params[key] === undefined && delete params[key]
    );

    // 调用 API 获取分类列表
    const res = await getCategoryList(params, true);

    const rows = Array.isArray(res?.data) ? res.data : [];
    listData.value = rows;

    const pageInfo = res?.page || {};
    pageParam.total = Number(pageInfo.total ?? rows.length ?? 0) || 0;
  } catch (error) {
    console.error('获取列表失败:', error);
    ElMessage.error('获取列表失败');
  } finally {
    pageParam.loading = false;
  }
};

/**
 * 获取类型名称
 */
const getLevelName = (level) => {
  const levelMap = {
    1: '大类',
    2: '中类',
    3: '品类',
    4: '商品',
  };
  return levelMap[level] || '--';
};

/**
 * 获取状态值
 */
const getStatusValue = (row) => {
  if (!row) return undefined;
  const value = row.status;
  if (value === '' || value === null || value === undefined) return undefined;
  const num = Number(value);
  return Number.isNaN(num) ? undefined : num;
};

/**
 * 获取状态展示文案
 */
const getStatusLabel = (row) => {
  if (!row) return '--';
  const statusValue = getStatusValue(row);
  if (statusValue === undefined) return '--';
  return statusValue === 1 ? '已生效' : '已停用';
};

/**
 * 查询操作
 */
const handleQuery = () => {
  pageParam.pageNo = 1;
  getListData();
};

/**
 * 分类类型 tabs 切换
 */
const handleCategoryTypeChange = () => {
  handleQuery();
};

/**
 * 重置搜索参数
 */
const handleReset = () => {
  Object.keys(initialSearchParams).forEach((key) => {
    searchParams[key] = initialSearchParams[key];
  });
};

/**
 * 分页大小改变
 */
const handleSizeChange = (val) => {
  pageParam.pageNo = 1;
  pageParam.pageSize = val;
  getListData();
};

/**
 * 当前页改变
 */
const handleCurrentChange = (val) => {
  pageParam.pageNo = val;
  getListData();
};

/**
 * 新增分类
 */
const handleAdd = () => {
  router.push({
    name: 'categoryManagementCreate',
    query: {
      categoryTypeCode: activeCategoryTypeCode.value,
    },
  });
};

/**
 * 查看详情
 */
const handleViewDetail = (row) => {
  router.push({
    name: 'categoryManagementDetail',
    query: {
      code: row.categoryCode,
      categoryTypeCode: activeCategoryTypeCode.value,
    },
  });
};

/**
 * 编辑分类
 */
const handleEdit = (row) => {
  router.push({
    name: 'categoryManagementEdit',
    query: {
      code: row.categoryCode,
      categoryTypeCode: activeCategoryTypeCode.value,
    },
  });
};

/**
 * 启用/停用分类
 */
const handleStatusChange = async (row) => {
  const currentStatus = getStatusValue(row);
  const action = currentStatus === 1 ? '停用' : '启用';

  try {
    await ElMessageBox.confirm(`确认${action}该分类吗？`, {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });

    // 停用时检查是否有子项
    if (currentStatus === 1) {
      // 这里可以添加检查子项的逻辑
      // 如果存在有效状态的子项，提示：存在生效的子项，不允许停用
    }

    const categoryId = row?.categoryId;
    if (!categoryId) {
      ElMessage.error('缺少分类ID，无法变更状态');
      return;
    }

    // 调用分类启用/停用接口
    const newStatus = currentStatus === 1 ? 0 : 1;
    const params = {
      id: categoryId,
      status: String(newStatus),
    };
    await toggleCategoryStatus(params, true);

    ElMessage.success(`${action}成功`);
    getListData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}失败:`, error);
      ElMessage.error(`${action}失败`);
    }
  }
};

/**
 * 导出
 */
const handleExport = async () => {
  try {
    const params = {
      userToken: getToken('token_op_login_key')
        ? getToken('token_op_login_key')
        : undefined,
      categoryCode: searchParams.code || undefined,
      categoryName: searchParams.name || undefined,
      categoryTypeCode:
        activeCategoryTypeCode.value || DEFAULT_CATEGORY_TYPE_CODE,
      level: searchParams.level !== '' ? Number(searchParams.level) : undefined,
      status:
        searchParams.status !== '' ? Number(searchParams.status) : undefined,
    };

    Object.keys(params).forEach(
      (key) => params[key] === undefined && delete params[key]
    );

    const res = await $api.post(
      '/item-center/category/export',
      params,
      false,
      'blob'
    );
    downloadFile(res.data, res.headers);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败');
  }
};

/**
 * 表头样式处理
 */
const handleHeaderCellClass = (params) => {
  if (sortField.has(params.column.property)) {
    params.column.order = sortField.get(params.column.property);
  }
};

/**
 * 初始化
 */
const init = async () => {
  await getCategoryTypeTabs();
  await getListData();
};

onMounted(() => {
  init();
});
</script>

<style lang="less" scoped>
.label_text {
  display: inline-block;
  text-align: right;
  width: 80px;
}
.category_type_tabs {
  margin-bottom: 16px;
}
.category_type_tabs :deep(.el-tabs__header) {
  margin: 0;
}
.search_btn_group {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
}
.search_btn_group .el-button + .el-button {
  margin-left: 12px;
}
/deep/.el-table th {
  background-color: #e5e5e5 !important;
}
</style>
